#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <fcntl.h>
#include <errno.h>
#include <sys/ipc.h>
#include <sys/sem.h>
#include "sem.h"
int fds[4];
void write_data(char temp, int flag)
{
    int num = temp - '0'; // 1 2 3 4
    for (int i = 0; i < 4; i++)
    {
        if (flag != 0 || i < num)
        {
            write(fds[i], &temp, 1);
        }
    }
}
void create_file()
{
    char temp[2];
    for (int i = 0; i < 4; i++)
    {
        temp[0] = 'A';
        temp[0] = temp[0] + i;
        fds[i] = open(temp, O_CREAT | O_RDWR | O_TRUNC, 0655);
        if (fds[i] < 0)
        {
            perror("open file error!");
            exit(1);
        }
    }
}
int main(int argc, char *argv[])
{
    create_file();
    int semid = creat_sem(4);
    // printf("%d\n",semid);
    int flag = 0;
    int count = 0;
    while (count < 5) 
    {
        p_sem(semid, atoi(argv[1]));
        printf("[pid %d] 当前p操作信号量编号 %d\n", getpid(), atoi(argv[1]));
        fflush(stdout); // 强制刷新输出缓冲区

        write_data(argv[3][0], flag);

        v_sem(semid, atoi(argv[2]));
        printf("[pid %d] 当前v操作信号量编号 %d\n", getpid(), atoi(argv[2]));
        fflush(stdout);

        sleep(5);
        flag = 1;
        count++;
    }
}
